var nowDate = getDay(0);
var pandianid;
var shopcode = sessionStorage.getItem("shopcode");
var userId = sessionStorage.getItem("userId");
//alert(shopcode)
var daibannum = 0,pingjianum = 0;
var starttimecalendar = new lCalendar();
var endtimecalendar = new lCalendar();
starttimecalendar.init({
	'trigger': '#startDate',
	'type': 'date',
	'minDate': '2021-01-01',
	'maxDate': '2099-12-31'
});
endtimecalendar.init({
	'trigger': '#endDate',
	'type': 'date',
	'minDate': '2021-01-01',
	'maxDate': '2099-12-31'
});
var _config ;
$.ajax({
	type : "post",
	data:JSON.stringify({"pageUrl":location.href.replace(/\\&/g,'%26'),"corp":sessionStorage.getItem("corp")}),
	contentType: "application/json; charset=utf-8",
	async: false,
	url : "../../dingding/getconfig",
	dataType : "json",
	success : function(suc) {
		console.log(suc);
		_config = suc.config;
	}
}); 
dd.config({
	agentId : _config.agentid,
	corpId : _config.corpId,
	timeStamp : _config.timeStamp,
	nonceStr : _config.nonceStr,
	signature : _config.signature,
	jsApiList : [ 'runtime.info','biz.util.uploadImage','biz.contact.complexPicker' ]
});
function ICalendarClick(){
	
}
$(document).ready(function(){  //界面切换
	$('#name').text(sessionStorage.getItem("name"));
	$('#startDate').val(nowDate);
	$('#endDate').val(nowDate);
 	if(sessionStorage.getItem("Creload")=='true'){
	     window.location.reload();
		 sessionStorage.setItem("Creload", false);
	}else{
		getPandianJiancha();
		getPandianJianchaPingjia();
		$('#menuDiv .row_w30').on('click',function(){
			$(this).siblings().removeClass('orange').removeClass('add_bd_o');
			$(this).addClass('orange').addClass('add_bd_o');
			if($(this).attr('showType') == 'pingjia'){
				$('#pingjiaDiv').show();
				$('#daibanDiv').hide();
				$('#wanchengDiv').hide();
			}else if($(this).attr('showType') == 'daiban'){
				$('#pingjiaDiv').hide();
				$('#daibanDiv').show();
				$('#wanchengDiv').hide();
			}else{
				$('#pingjiaDiv').hide();
				$('#daibanDiv').hide();
				$('#wanchengDiv').show();
			}
		});
		$('#daibanButton').on('click',saveDaibanFlag);
  }
	
});
//查询门店盘点信息
function getPandianJiancha(){
	var sendData = {};
	sendData.shopcode=shopcode;
	sendData.pandianDate=nowDate;
//	sendData.flag=3;
	$.ajax({
		url: "../pandianevery/getPandianJiancha"
		,type:'post'
		,async: false
		,data:JSON.stringify(sendData)
		,contentType: "application/json; charset=utf-8"
		,dataType:'json'
		,success: function(res){
			console.log(res)
			
			if(res.success){
				var resdata = res.data;
				if(pandianid == undefined || pandianid == ''){
					pandianid = resdata[0].id;
				}
				if(resdata[0].flag == 3){
					getPandianJianShopDaibanList();
				}
			}else{
//				layer.alert(res.message);
				getPandianJianShopDaibanList();
			}
		}
		,error:function(XMLHttpRequest, textStatus, errorThrown) {
			 console.log(XMLHttpRequest);
			 console.log(textStatus);
			 console.log(errorThrown);
			 hideloading();
		}
	});
	
}
//获取门店待办信息
function getPandianJianShopDaibanList(){
	showloading();
	var sendData = {};
	sendData.flag = 0;
	if(pandianid != undefined && pandianid != ''){
		sendData.pandianid = pandianid;
	}else{
		sendData.pandianDate = getDay(1);
		sendData.shopcode = shopcode;
	}
	$.ajax({
		url: "../pandianevery/getPandianJianShopDaibanList"
		,type:'post'
		,dataType:'json'
//		,async: false
		,contentType: "application/json; charset=utf-8"
		,data:JSON.stringify(sendData) 
		,success: function(res){
			console.log(res)
			try {
				if(res.success){
					var data = res.data;
					$('#daiban_div').empty();
					if(data != undefined && data.length > 0){
						daibannum = data.length;
						if(pandianid == undefined || pandianid == ''){
							pandianid = data[0].pandianid;
						}
						addPandianDaiban(data);
						$('#daibanButton').show();
					}
					$('#daibannum').text(daibannum);
				}else{
//					layer.msg(res.message);
				}
			} catch (e) {
				console.log(e)
			} finally{
				hideloading();
			}
		}
    });
}
function addPandianDaiban(jsonparse){
	for(var i = 0 ;i<jsonparse.length;i++){
		var imgStr = '		<div class="widget-box add_mar_tb7p">'
			+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
			+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;图片上传</h5><span class="red"></span>'						  
			+'				<div class="widget-toolbar no-border" style="margin-top: 5px"  onclick="openphoto('+jsonparse[i].itemid+')">'
			+'					<img src="../../genius/style/mobile_page/assets/images/photo.png" />'
			+'				</div>'
			+'			</div>'				
			+'			<div class="widget-body zhediebox1">'					
			+'				<div class="widget-main pd_div" id="paizhapoUrl'+jsonparse[i].itemid+'" >'
			+'					<div class="clearfix"></div>'						
			+'				</div>'						
			+'			</div>'					
			+'		</div>';
		
		var thenum = $('div[daibanitemDiv]').length;
		$('#daiban_div').append('<div class="col_box" daibanitemDiv="'+jsonparse[i].itemid+'">'
				+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_mar_tb7p">'
				+'<h5 class="black">门店待办事项'+(thenum+1)+'</h5>'
//				+'<div deleteIndex="'+thenum+'" class="bt_delete bg_orange">删除</div><div class="clearfix"></div>'
				+'</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;条款</h5><span class="red" bitian></span>'
				+'				<div class="pull-right add_bor_none" style="width: 70%;margin-right: 2%; color:#474747; line-height:26px;">'+jsonparse[i].itemname+'</div>'
				+'			</div>'
				+'		</div>'
				+'		<div class="widget-box add_mar_tb7p">'
				+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
				+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;回复内容</h5><span class="red" bitian></span>'
				+'				<input type="text" placeholder="请输入回复内容" jsonKey="shophuifu" autocomplete="off"   class="pull-right add_bor_none" style="width: 70%;margin-right: 2%"/>'
				+'			</div>'
				+'		</div>'
				+imgStr				
				+'</div>');
	
	}
}
//打开钉钉拍照
function openphoto(index){
	
	dd.ready(function(){
		dd.biz.util.uploadImage({
		    compression: false,//(是否压缩，默认为true)
		    quality: 100, // 图片压缩质量, 
		    resize: 100, // 图片缩放率
		    stickers: {   // 水印信息
		        time: nowDate,
		        username: sessionStorage.getItem("name")
		    },
		    onSuccess : function(result) {
				$('#paizhapoUrl'+index+' .clearfix').remove()
				$('#paizhapoUrl'+index).append('<div class="wig_img">'
						+'<div class="img_box">'
						+'<img daibanimg alt="100x100" src="'+result[0]+'" onclick="showAllPic(\''+result[0]+'\')"/>'
						+'<img class="close_b" src="../../genius/style/mobile_page/assets/images/close.png" onclick="deletePhoto(this)">'
						+'</div>'
						+'</div>');
				$('#paizhapoUrl'+index).append('<div class="clearfix"></div>');
		    },
		    onFail : function(err) {}
		});
	});
	dd.error(function(err) {
		alert(JSON.stringify(err));
		
//		alert('dd error: ' + JSON.stringify(err));
	});
}	
//删除图片
function deletePhoto(obj){
	dd.device.notification.confirm({
	    message: "删除图片吗",
	    title: "提示",
	    buttonLabels: ['是', '否'],
	    onSuccess : function(result) {
	    	if(result.buttonIndex == '0'){
	    		var index = $(obj).parent().parent().index();
	    		$(obj).parent().parent().remove();
	    		photoUrl.splice(index,1);
	    	}
	        
	    },
	    onFail : function(err) {}
	});
	 
}
//预览图片
function showAllPic(imgOne){
	dd.biz.util.previewImage({
		urls: imgOne.split(','),//图片地址列表
		current: imgOne,//当前显示的图片链接
		onSuccess : function(result) {
			/**/
		},
		onFail : function(err) {}
	})
}
//完成待办
function saveDaibanFlag(){
	showloading();
	try {
		var sendData = {};
		var insertArray = [];
		var checkFlag = true;
		$('div[daibanitemDiv]').each(function(i,obj){
			if(checkFlag){
				var insertJson = {};
				$(obj).find('[jsonKey]').each(function(j,el){
					if($(el).parent().find('span[bitian]').text() == '*' && $(el).val() == ''){
						layer.msg($(el).parent().find('h5').text()+"为必填项");
						checkFlag = false;
						return false;
					}else{
						var key = $(el).attr('jsonKey');
						insertJson[key] = $(el).val();
						//console.log(insertJson);
						key = null;
					}
				});
				if(checkFlag){
					//设置图片
					var img = [];
					$(obj).find('img[daibanimg]').each(function(j,el){
						img.push($(el).attr('src'));
					});
					insertJson.shopimg = img;
					
				}
				insertJson.pandianid = pandianid;
				insertJson.lrr = userId;
				insertJson.shopcode = shopcode;
				insertJson.flag = 1;
				insertJson.itemid = $(obj).attr('daibanitemDiv');
				insertArray.push(insertJson);
			}else{
				return false;
			}
		});
		console.log(sendData);
		if(checkFlag){
			sendData.dataArray = insertArray;
			sendData.flag = 1;
			sendData.pandianid = pandianid;
			$.ajax({
				url: "../pandianevery/editPandianJianShopDaiban"
				,type:'post'
				,dataType:'json'
				,async: false
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify(sendData) 
				,success: function(res){
					console.log(res)
					if(res.success){
						window.location.href='toShop_index';
					}else{
						hideloading();
						layer.alert(res.message);
					}
				}
		    });
		}
/*		console.log(insertArray.length);*/
	} catch (e) {
		console.log(e)
	} finally{
		hideloading();
	}
}
//评价信息列表
function getPandianJianchaPingjia(){
	showloading();
	var sendData = {};
	sendData.pingjiaFlag = 0;
	sendData.shopcode = shopcode;
	sendData.flag = 7;
	sendData.endDate = $('#endDate').val();
	sendData.startDate = $('#startDate').val();
	$.ajax({
		url: "../pandianevery/getPandianJiancha"
		,type:'post'
		,dataType:'json'
//		,async: false
		,contentType: "application/json; charset=utf-8"
		,data:JSON.stringify(sendData) 
		,success: function(res){
			console.log(res)
			try {
				$('#pingjiaTable').empty();
				if(res.success){
					var resdata = res.data;
					if(pandianid == undefined || pandianid == ''){
						pandianid = resdata[0].id;
					}
					for (var i = 0; i < resdata.length; i++) {
						if(resdata[i].pingjiaFlag == '0'){
							resdata[i].pingjiaFlagName = '去评价';
							pingjianum ++;
						}else{
							resdata[i].pingjiaFlagName = '查看评价';
						}
						$('#pingjiaTable').append('<tr class="thin-border-bottom">'
								+'	<td>'+resdata[i].pandianDate+'</span></td>'
								+'	<td>'+resdata[i].xgrname+'</span></td>'
								+'	<td style="" class="orange" onclick="inPingjia('+resdata[i].pingjiaFlag+')">'+resdata[i].pingjiaFlagName+'</td>'
								+'</tr>');
					}
					$('#pingjianum').text(pingjianum);
					
				}else{
//					layer.alert(res.message);
				}
			} catch (e) {
				console.log(e)
			} finally{
				hideloading();
			}
		}
    });
}
//跳转到评价页面
function inPingjia(pingjiaFlag){
	window.location.href='toJiancha_pingjia?pandianid='+pandianid+"&pingjiaFlag="+pingjiaFlag;
}